package com.hzw.saas.web.admin.user.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzw.saas.api.user.ICustomerLevelService;
import com.hzw.saas.api.user.ICustomerService;
import com.hzw.saas.api.user.IStaffService;
import com.hzw.saas.api.user.IUserAccountService;
import com.hzw.saas.api.user.bo.CustomerBO;
import com.hzw.saas.api.user.bo.CustomerLevelBO;
import com.hzw.saas.api.user.bo.StaffBO;
import com.hzw.saas.api.user.bo.UserAccountBO;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.util.ExcelUtils;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.security.utils.SecurityUtils;
import com.hzw.saas.web.admin.security.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping
@RequiredArgsConstructor
@Api(tags = "导出")
public class ExportController {
    @Autowired
    private IUserAccountService userAccountService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ICustomerLevelService customerLevelService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private IStaffService staffService;
    @ApiOperation(value = "导出注册信息")
    @ApiOperationSort(0)
    @GetMapping("/exportUserRegister")
    @SysLog(operation = "导出注册信息")
    public ResponseEntity<Void> exportUserRegister( @RequestParam(required = false ) List<String> userIds,
                                                    @RequestParam(required = false) String fuzzyString,
                                                    @RequestParam(required = false) List<String> levelIds,
                                                    @RequestParam(required = false) Boolean isOpen,
                                                    @RequestParam(required = false)  List<String> channelTypes,
                                                    HttpServletResponse response)throws IOException {
        ArrayList<String> stringArrayList = new ArrayList<>();
        if (permissionService.hasAny("customer:list:self")){
            StaffBO byId = staffService.getById(SecurityUtils.getUserId());
            if (byId != null){
                stringArrayList.add(byId.getPid());
                if (StrUtil.isNotBlank(byId.getStaffPhoneNo())){
                    stringArrayList.add(byId.getStaffPhoneNo());
                }
                if (CollectionUtil.isNotEmpty(byId.getStaffPhoneNoList())){
                    stringArrayList.addAll(byId.getStaffPhoneNoList());
                 }
            }
        }
        Page<CustomerBO> customers = new Page<>();
        if (StringUtils.isBlank(fuzzyString) &&
            CollectionUtils.isEmpty(levelIds) &&
            isOpen == null &&
            CollectionUtils.isEmpty(channelTypes) &&
            CollectionUtils.isEmpty(userIds)&&CollectionUtil.isEmpty(stringArrayList)) {
            IPage<CustomerBO> customerBOIPage = customerService.efficientPageCustomers(PageParam.getBigPageParam());
            customers.setRecords(customerBOIPage.getRecords());
            customers.setSize(customerBOIPage.getSize());
            customers.setTotal(customerBOIPage.getTotal());
            customers.setCurrent(customerBOIPage.getCurrent());
            customers.setPages(customerBOIPage.getPages());
        }else {
            IPage<CustomerBO> pageCustomers = customerService.pageCustomers(PageParam.getBigPageParam(), fuzzyString, levelIds, isOpen, channelTypes, userIds,stringArrayList);
            customers.setRecords(pageCustomers.getRecords());
            customers.setSize(pageCustomers.getSize());
            customers.setTotal(pageCustomers.getTotal());
            customers.setCurrent(pageCustomers.getCurrent());
            customers.setPages(pageCustomers.getPages());
        }
        if (CollectionUtil.isNotEmpty(customers.getRecords())){
            List<CustomerLevelBO> customerLevelBOS = customerLevelService.listLevels();
            List<String> collect = customers.getRecords().stream().map(CustomerBO::getUserId).collect(Collectors.toList());
            List<UserAccountBO> userAccounts = userAccountService.getUserAccounts(collect);
            customers.getRecords().forEach(customerBO -> {
                if (StrUtil.isNotBlank(customerBO.getChannelType())) {
                    if (customerBO.getChannelType().equals("A")) {
                        customerBO.setChannelType("用户注册");
                    }
                    if (customerBO.getChannelType().equals("B")) {
                        customerBO.setChannelType("后台开通");
                    }
                    if (customerBO.getChannelType().equals("C")) {
                        customerBO.setChannelType("扫码推广");
                    }
                    if (customerBO.getChannelType().equals("D")) {
                        customerBO.setChannelType("单机软件");
                    }
                }

                if(CollectionUtil.isNotEmpty(userAccounts)){
                    userAccounts.forEach(userAccountBO -> {
                        if (userAccountBO.getUserId().equals(customerBO.getUserId())){
                            customerBO.setRegisterDate(DateUtil.format(userAccountBO.getRegisteredDate(),"yyyy-MM-dd HH::mm::SS"));
                        }
                    });
                }

                if (CollectionUtil.isNotEmpty(customerLevelBOS)){
                    customerLevelBOS.forEach(customerLevelBO -> {
                        if (customerBO.getCustomerLevel().equals(customerLevelBO.getLevelId())){
                            customerBO.setCustomerLevelText(customerLevelBO.getLevelText());
                        }
                    });
                }
            });
        }
        ExcelUtils.exportExcel(customers.getRecords(),"客户信息","客户信息", CustomerBO.class,"注册信息",response);
        return ResponseEntity.ok().build();
    }

}
